/*
 * MrimClient.java
 *
 * Created on 26 Апрель 2009 г., 19:50
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

// #sijapp cond.if protocols_MRIM is "true" #
// #sijapp cond.if modules_CLIENTS is "true" #
package protocol.mrim;

import DrawControls.icons.*;
import jimm.comm.Config;
import jimm.comm.StringConvertor;
import jimm.modules.*;

/**
 *
 * @author Vladimir Krukov
 */
public class MrimClient {
    private static final ImageList clientIcons = ImageList.createImageList("/mrim-clients.png");
    private static final String[] clientIds;
    private static final String[] clientNames;
    static {
        Config cfg = new Config().load("/mrim-clients.txt");
        clientIds = cfg.getKeys();
        clientNames = cfg.getValues();
    }
    public static final MrimClient noneClient = new MrimClient();
    private static final byte CLI_NONE = -1;

    private byte clientIndex = CLI_NONE;
    private String version = "";
    /** Creates a new instance of MrimClient */
    private MrimClient() {
    }

    private static final String getValue(String str, String key) {
        String fullKey = key + "=\"";
        int keyIndex = str.indexOf(fullKey);
        int valueIndex = keyIndex + fullKey.length();
        int endIndex = str.indexOf('"', valueIndex);
        if ((-1 == keyIndex) || (-1 == endIndex)) {
            return "";
        }
        return str.substring(valueIndex, endIndex);
    }
    static public MrimClient createClient(MrimClient prev, String caps) {
        if (null == prev) {
            prev = noneClient;
        }
        if (StringConvertor.isEmpty(caps)) {
            return noneClient;
        }

        String clientClient = getValue(caps, "cl" + "ient");
        String clientName = getValue(caps, "n" + "ame");
        byte clientIndex = CLI_NONE;
        for (byte idIndex = 0; idIndex < clientIds.length; ++idIndex) {
            if (-1 != clientName.indexOf(clientIds[idIndex])) {
                clientIndex = idIndex;
                break;
            }
            if (-1 != clientClient.indexOf(clientIds[idIndex])) {
                clientIndex = idIndex;
                break;
            }
        }
        if (CLI_NONE == clientIndex) {
            // #sijapp cond.if modules_DEBUGLOG is "true"#
            DebugLog.println("Unknown client: " + caps);
            // #sijapp cond.end#
            return noneClient;
        }
        MrimClient result = (noneClient == prev) ? new MrimClient() : prev;
        result.clientIndex = clientIndex;
        result.version = getValue(caps, "v" + "ersion");
        return result;
    }
    
    public Icon getIcon() {
        return clientIcons.iconAt(clientIndex);
    }
    public String getName() {
        if (CLI_NONE == clientIndex) {
            return null;
        }
        return (clientNames[clientIndex] + " " + version).trim();
    }
}
// #sijapp cond.end #
// #sijapp cond.end #